import { fetchGetMccMeetingLogDetail, fetchGetReservationLogDetail } from '@/api/sysLog'
import { Modal } from '@kedacom/react-next'
import React, { useEffect, useState } from 'react'
import { StyledWrap, CopyIcon } from './style'
import { ReservationLogData, MccLogDetailListData } from '../../interface'
import copy from 'copy-to-clipboard'
import { createRange } from '@/utils'
import { t } from 'i18next'

export type LogDetailModalProps<T> = {
	data: T
	open: boolean
	setOpen: (val: boolean) => void
} & ({ type: 'reservation' } | { type: 'mcc'; meetingMoid: string })

export default function LogDetailModal<T extends ReservationLogData | MccLogDetailListData | null>(
	props: LogDetailModalProps<T>
) {
	const { data, open, type, setOpen } = props
	const [detail, setDetail] = useState('')

	useEffect(() => {
		if (data) {
			if (type === 'mcc') {
				fetchGetMccMeetingLogDetail(props.meetingMoid, data.id).then((res) => {
					if (res) {
						setDetail(res.detail)
					}
				})
			} else {
				fetchGetReservationLogDetail(data.id).then((res) => {
					if (res) {
						setDetail(res)
					}
				})
			}
		}
	}, [data?.id])

	const onCopy = () => {
		let text = (document.querySelector('#reservation-text') as any)?.innerText ?? ''
		copy(text) && createRange(document.querySelector('#reservation-text'))
	}

	return (
		<Modal
			open={open}
			className="log-detail-modal"
			width={550}
			height={470}
			title={t('日志详细')}
			okText={false}
			cancelText={t('关闭')}
			onCancel={() => {
				setOpen(false)
			}}
		>
			<StyledWrap>
				<div className="line">
					<span className="label">{t('操作用户')}</span>
					<span className="value">{data?.operator}</span>
				</div>
				<div className="line">
					<span className="label">{t('操作时间')}</span>
					<span className="value">{data?.operating_time}</span>
				</div>
				<div className="line">
					<span className="label">{t('操作内容')}</span>
					<span className="value">{data?.operational}</span>
				</div>
				<div className="line">
					<span className="label">{t('操作结果')}</span>
					<span className="value">{data?.operation_result}</span>
					<CopyIcon className="copy-btn" title={t('复制详情')} onClick={onCopy} />
				</div>
				{data?.result_fail && <div className="fail">{data.result_fail}</div>}
				<div
					className="text"
					id="reservation-text"
					dangerouslySetInnerHTML={{
						__html: detail,
					}}
				></div>
			</StyledWrap>
		</Modal>
	)
}
